<template>
  <div class="main-box">
    <TreeFilter
      ref="treeFilter"
      label="orgName"
      :title="$t('message.orgInfo.title')"
      :default-value="queryParams.parentId"
      :data="orgTree"
      :default-expand="false"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTableRef"
        :title="$t('message.orgInfo.title')"
        :columns="columns"
        :request-api="orgApi.page"
        :init-param="queryParams"
        :data-callback="dataCallback"
      >
        <template #tableHeader>
          <el-button size="default" type="success" class="ml10" @click="openAddOrg()" v-auth="'system:org:add'">
            <el-icon><CirclePlus /></el-icon>{{ $t("message.commonBtn.add") }}
          </el-button>
          <el-button type="primary" plain @click="batchAdd" size="default" v-auth="'system:org:add'">
            <el-icon><Upload /></el-icon>
            {{ $t("message.commonBtn.batchImport") }}
          </el-button>
        </template>
        <template #operation="scope">
          <el-space>
            <el-button size="small" text type="primary" @click="openEditOrg(scope.row)" v-auth="'system:org:update'">
              <el-icon><Edit /></el-icon>
              {{ $t("message.commonBtn.edit") }}
            </el-button>
            <el-button size="small" text type="danger" @click="delOrg(scope.row)" v-auth="'system:org:delete'">
              <el-icon><Delete /></el-icon>
              {{ $t("message.commonBtn.delete") }}
            </el-button>
          </el-space>
        </template>
      </ProTable>
      <EditOrg
        ref="editOrgRef"
        :title="state.editOrgTitle"
        :org-data="orgTree"
        :dict-data="state.dictData"
        @refresh="refreshOrgData"
      />
      <ImportExcel ref="importExcelRef" />
    </div>
  </div>
</template>

<script lang="tsx" setup name="systemOrg">
import { reactive, ref, watchEffect, defineAsyncComponent } from "vue";
import { ElMessageBox } from "element-plus";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { feature } from "@/utils/axios-utils";
import { DictData, SysOrg } from "@/api-services/models/system";
import { useI18n } from "vue-i18n";
import ProTable from "@/components/ProTable/index.vue";
import orgApi from "@/api-services/apis/system/orgApi";
import dictDataApi from "@/api-services/apis/system/dictDataApi";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { SqlSugarPagedList, UnifyResult } from "@/api-services/unifyResult";
import { CirclePlus, Delete, Edit, Upload } from "@element-plus/icons-vue";
import { NotificationError, NotificationSuccess } from "@/utils/notification";
const ImportExcel = defineAsyncComponent(() => import("@/components/ImportExcel/index.vue"));
const EditOrg = defineAsyncComponent(() => import("@/views/system/org/component/editOrg.vue"));
const { t } = useI18n();
const proTableRef = ref<ProTableInstance>();
const editOrgRef = ref<InstanceType<typeof EditOrg>>();
const orgTree = ref<Array<SysOrg.SysOrg>>([]);
const treeFilter = ref<InstanceType<typeof TreeFilter> | null>(null);
const queryParams = reactive({
  parentId: -1
});
const state = reactive({
  loading: false,
  orgData: [] as Array<SysOrg.SysOrg>, // 机构列表数据
  orgTreeData: [] as Array<SysOrg.OrgSimpleInfo>, // 机构树所有数据
  dictData: [] as Array<DictData.SysDictData>, //字典数据
  editOrgTitle: "",
  initOrg: [] as Array<SysOrg.SysOrg>
});

const queryOrgType = async () => {
  const res = await dictDataApi.getDatalistByType("orgType");
  state.dictData = res.data.data ?? [];
};
watchEffect(() => {
  queryOrgType();
});
//数据回显处理
const dataCallback = (queryRes: UnifyResult<SqlSugarPagedList<SysOrg.SysOrg>>) => {
  const data = queryRes.data;
  return {
    items: data.items,
    totalCount: data.totalCount,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize
  };
};
const columns: ColumnProps<SysOrg.SysOrg>[] = [
  {
    prop: "orgName",
    label: t("message.orgInfo.orgName"),
    search: {
      el: "input",
      key: "orgName",
      props: { placeholder: t("message.orgInfo.orgName") }
    }
  },
  {
    prop: "category",
    label: t("message.orgInfo.orgType"),
    render: scope => {
      const data = state.dictData.filter(item => item.value == scope.row.category)[0];
      return (
        <el-tag size={data?.tagSize} type={data?.tagType}>
          {data?.name}
        </el-tag>
      );
    }
  },
  { prop: "remark", label: t("message.orgInfo.remark") },
  { prop: "sortCode", label: t("message.orgInfo.sortCode") },
  { prop: "updateTime", label: t("message.orgInfo.editTime") },
  { prop: "operation", label: t("message.commonBtn.oper"), fixed: "right" }
];

const changeTreeFilter = (val: number) => {
  proTableRef.value!.pageable.pageIndex = 1;
  queryParams.parentId = val;
};

const refreshOrgData = async () => {
  handleQuery();
  // 编辑删除后更新机构数据
  queryOrgTree();
};
// 查询操作
const handleQuery = async () => {
  proTableRef.value?.getTableList();
};

// 打开新增页面
const openAddOrg = () => {
  state.editOrgTitle = t("message.orgOperation.addOrg");
  editOrgRef.value?.openDialog({});
};

// 打开编辑页面
const openEditOrg = (row: SysOrg.SysOrg) => {
  state.editOrgTitle = t("message.orgOperation.editOrg");
  editOrgRef.value?.openDialog(row);
};

// 删除
const delOrg = (row: SysOrg.SysOrg) => {
  ElMessageBox.confirm(`${t("message.orgAlter.isDeleteOrg")}:【${row.orgName}】?`, t("message.commontInfo.info"), {
    confirmButtonText: t("message.orgAlter.confirm"),
    cancelButtonText: t("message.orgAlter.cancel"),
    type: "warning"
  })
    .then(async () => {
      const [err] = await feature(orgApi.delete({ id: row.id }));
      if (err) {
        NotificationError(err.message);
      } else {
        NotificationSuccess(t("message.orgAlter.deleteSuccess"));
        refreshOrgData();
      }
    })
    .catch();
};

// 批量添加用户
const importExcelRef = ref<InstanceType<typeof ImportExcel>>(); //ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: t("message.orgInfo.org"),
    tempApi: orgApi.templateDownload,
    importApi: orgApi.batchImport,
    getTableList: proTableRef.value?.getTableList,
    errorDownloadApi: orgApi.errorFileDownload
  };
  importExcelRef.value?.acceptParams(params);
};
const queryOrgTree = async () => {
  const res = await orgApi.orgTree();
  orgTree.value = res.data.data;
};
onMounted(async () => {
  await queryOrgTree();
});
</script>
